/*
 * (c) ralfoide gmail com, 2008
 * Project: gamez/packer
 * License TBD
 */

package com.alfray.gamez.util;

import java.util.Iterator;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Returns a <em>real</em> iterator from an XML {@link NodeList}.
 * <p/>
 * This is so basic and necessary it's surprising it's not part of the dom.
 */
public class NodesIterator implements Iterator<Node>, Iterable<Node> {

	private final NodeList mNodeList;
	private int mIndex;

	/** Constructs a NodeListIterator wrapping an actual NodeList. */
	public NodesIterator(NodeList nodeList) {
		mNodeList = nodeList;
		mIndex = 0;
	}

	/**
	 * @return the wrapped node list
	 */
	public NodeList getNodeList() {
		return mNodeList;
	}

	/**
	 * @return The current internal index, range [ 0 .. getNodeList().getLength() ]
	 */
	public int getIndex() {
		return mIndex;
	}
	
	/**
	 * @return True if the node list is not null and the end has not been reached.
	 */
	public boolean hasNext() {
		return mNodeList != null && mIndex < mNodeList.getLength();
	}

	/**
	 * @return The next node.
	 * @throws IndexOutOfBoundsException if the end has already been reached.
	 */
	public Node next() {
		return mNodeList.item(mIndex++);
	}

	/**
	 * Not supported.
	 * 
	 * @throws UnsupportedOperationException
	 */
	public void remove() {
		throw new UnsupportedOperationException("NodesIterator does not support removal");
	}

	/**
	 * Implements {@link Iterable} but returning this iterator.
	 */
	public Iterator<Node> iterator() {
		return this;
	}
}
